package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import com.etoak.common.core.UserVo.PageVO;
import com.etoak.common.web.exception.CustomException;
import com.etoak.entity.Dishes;
import com.etoak.mapper.DishesMapper;
import com.etoak.service.DishesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.vo.DishesVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * DishesService 服务实现类
 *
 * @author et2403
 * @since 2024-08-14
 */
@Service
public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes> implements DishesService {

    @Override
    public void add(Dishes dishes) {
        Dishes savedDishes = getByName(dishes.getName());
        if(ObjectUtils.isNotEmpty(savedDishes)){
            throw new CustomException("菜品名称已存在");
        }
        dishes.setCreateTime(DateUtil.now());
        this.save(dishes);
    }

    @Override
    public PageVO<DishesVO> getList(int pageNum, int pageSize, Dishes dishes) {
        PageHelper.startPage(pageNum,pageSize);
        List<DishesVO> dishesVOList = baseMapper.getList(dishes);
        PageInfo<DishesVO> pageInfo = new PageInfo<>(dishesVOList);
        return new PageVO<>(pageInfo.getPageNum(),
                pageInfo.getPageSize(),
                dishesVOList,
                pageInfo.getTotal());
    }

    @Override
    public void update(int id, Dishes dishes) {
        if(ObjectUtils.isEmpty(this.getById(id))){
            throw new CustomException("菜品不存在!!");
        }

        /* 验证菜品名称 */
        String dishesName = dishes.getName();
        if(StringUtils.isNotEmpty(dishesName)){
            Dishes savedDishes = this.getByName(dishesName);
            if(ObjectUtils.isNotEmpty(savedDishes) && !savedDishes.getId().equals(id)){
                throw new CustomException("菜品名称已存在");
            }

        }
        dishes.setId(id);
        dishes.setUpdateTime(DateUtil.now());
        this.updateById(dishes);
    }

    @Override
    public void delete(int id) {
        if(ObjectUtils.isEmpty(this.getById(id))){
            throw new CustomException("菜品不存在!!");
        }
        this.removeById(id);
    }

    private Dishes getByName(String name){
        return lambdaQuery().eq(Dishes::getName,name).one();
    }

}
